package com.teamwhole.modules.sys.service;

import java.util.Collection;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.teamwhole.common.security.Digests;
import com.teamwhole.core.shiro.session.SessionDAO;
import com.teamwhole.core.persistence.service.BaseService;
import com.teamwhole.common.utils.Encodes;

@Service
@Transactional(readOnly = true)
public class SystemService extends BaseService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;
	
	@Autowired
	private SessionDAO sessionDao;
	
    // -- System Service --//
	
    /**
     * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
     * 
     * @param plainPassword
     * @return
     */
    public static String entryptPassword(String plainPassword) {
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
        return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
    }

    /**
     * 验证密码
     * 
     * @param plainPassword 明文密码
     * @param password 密文密码
     * @return 验证成功返回true
     */
	public static boolean validatePassword(String plainPassword, String password) {
		byte[] salt = Encodes.decodeHex(password.substring(0, 16));
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return password.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
	}
	
	/**
     * 获得活动会话
     * @return
     */
    public Collection<Session> getActiveSessions(){
        return sessionDao.getActiveSessions(false);
    }

	public SessionDAO getSessionDao() {
		return sessionDao;
	}
	
}